package com.abel.lock;

import java.util.concurrent.CountDownLatch;

/**
 * @author xiachao
 * @date 2019/2/3
 */
public class Main {

    private CountDownLatch downLatch;

    private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();


    public void testThreadLocal(){
        for(int i=0;i<2;i++){
            threadLocal.set(i);
            new Thread(new ThreadTask(threadLocal)).start();
        }
    }

    public void test() throws InterruptedException {
        this.downLatch = new CountDownLatch(3);
        new Thread(new Task(downLatch, 1)).start();
        new Thread(new Task(downLatch, 2)).start();
        new Thread(new Task(downLatch, 3)).start();

        this.downLatch.await();
        System.out.println("All tasks completed");
    }

    public static void main(String[] args) throws InterruptedException {
        //new Main().test();
        new Main().testThreadLocal();
    }

    public class Task implements Runnable{

        private CountDownLatch downLatch;
        private int num;
        public Task(CountDownLatch downLatch, int num){
            this.downLatch = downLatch;
            this.num = num;
        }

        @Override
        public void run() {
            System.out.println("Thread of "+num+" complete");
            this.downLatch.countDown();
        }
    }


    public class ThreadTask implements Runnable{
        private ThreadLocal<Integer> local;

        public ThreadTask(ThreadLocal<Integer> local){
            this.local = local;
        }

        @Override
        public void run(){
            System.out.println(this.local.get());
        }
    }

}
